<template>
  <div class="content-wrap">
    <!-- 操作框 -->

    <operate-area
      ref="operateArea"
      :btn-text="btnText"
      :placeholder-text="'ID/姓名'"
      :search-value.sync="searchVal"
      @addUser="addUser"
      @deleteUser="delUser"
      @disableUser="disUser"
      @enableUser="enUser"
      @resetUser="handleReset"
      @queryData="getUserList"
    ></operate-area>

    <!-- table -->
    <!-- :row-class-name="tableRowClassName" -->
    <el-table
      v-loading="tLoading"
      :data="tableData"
      @row-click="checkUserDetail"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        :selectable="selectable"
        class="first"
        min-width="48"
        type="selection"
      ></el-table-column>

      <el-table-column
        :reserve-selection="true"
        class="cup"
        label="#"
        min-width="48"
        type="index"
      >
        <template slot-scope="scope">
          <span>{{ scope.$index + (pageNo - 1) * pageSize + 1 }}</span>
        </template>
      </el-table-column>

      <el-table-column
        :show-overflow-tooltip="true"
        class="cup"
        label="登录名"
        prop="loginName"
        width="120"
      ></el-table-column>

      <el-table-column
        class="cup"
        label="姓"
        prop="surname"
        width="72"
        :show-overflow-tooltip="true"
      ></el-table-column>

      <el-table-column
        class="cup"
        label="名"
        prop="name"
        width="96"
        :show-overflow-tooltip="true"
      ></el-table-column>

      <el-table-column
        :show-overflow-tooltip="true"
        class="cup"
        label="邮箱"
        min-width="120"
        prop="email"
      ></el-table-column>

      <el-table-column
        class="cup"
        label="手机号码"
        prop="telephone"
        width="120"
      ></el-table-column>

      <el-table-column
        :filter-append-to-body="false"
        :filter-method="filterTag"
        :filters="[
          { text: '启用', value: '1' },
          { text: '禁用', value: '0' }
        ]"
        filter-placement="bottom-end"
        label="状态"
        prop="status"
        width="96"
      >
        <template
          slot="header"
          slot-scope="{ column }"
        >
          <span>{{ column.label }}</span>
          <i class="iconfont iconicon_filtrate fs13"></i>
        </template>
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.status === '1' ? 'success' : 'info'"
            disable-transitions
          >{{ scope.row.status === "1" ? "启用" : "禁用" }}</el-tag>
        </template>
      </el-table-column>     

      <el-table-column
        fixed="right"
        label="操作"
        width="60"
      >
        <template slot-scope="scope">
          <el-tooltip
            content="另存"
            placement="top"
          >
            <i
              class="iconfont iconicon_save fs16"
              @click.stop="copySave(scope.row)"
            ></i>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!--分页组件-->
    <pagination
      :page.sync="pageNo"
      :total="total"
      @pagination="getUserList"
    />

    <el-dialog
      :visible.sync="resetPswDialog"
      append-to-body
      class="dialog-wrap resetsdialog"
      title="重置密码"
      width="400px"
      @close="closeResetDIALOG"
    >
      <el-form ref="pass" :model="pswForm" :rules="pswRules" label-width="120px">
        <el-form-item label="新密码" prop="password">
          <el-input v-model="pswForm.password" show-password placeholder="请输入新密码" autocomplete="off" style="width:250px" @keyup.native="pswForm.password = pswForm.password.replace(/[^a-zA-Z0-9]/g,'')"></el-input>
        </el-form-item>
        <el-form-item label="再次输入新密码" prop="pswSecond" style="margin: 0 0 4px 0;">
          <el-input v-model="pswForm.pswSecond" show-password placeholder="请再次输入新密码" autocomplete="off" style="width:250px" @keyup.native="pswForm.pswSecond = pswForm.pswSecond.replace(/[^a-zA-Z0-9]/g,'')"></el-input>
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <operate-btn
          @cancel="closeResetDialog"
          @submitSave="submitReset"
        ></operate-btn>
      </div>
    </el-dialog>

    <!-- 添加用户 -->
    <drawer
      :before-close="handleClose"
      :close-on-press-escape="false"
      :visible.sync="dialogAddUser"
      class="add-user-drawer"
      custom-class="demo-drawer"
      direction="rtl"
      size="368px"
      title="添加用户"
      @close="closeDrawer"
    >
      <div class="demo-drawer__content">
        <user-info
          ref="addUser"
          :current-user="formAddUser"
          :is-edit="false"
        ></user-info>
        <footer-btn
          ref="editFooter"
          @cancel="cancelAdd"
          @submitSave="submitAddUser"
        ></footer-btn>
      </div>
    </drawer>

    <!-- 用户详情 -->
    <drawer
      :before-close="handleCloseDetail"
      :close-on-press-escape="false"
      :title="currentUser.userName"
      :visible.sync="dialogUserDetail"
      custom-class="demo-drawer"
      direction="rtl"
      size="416px"
    >
      <div class="demo-drawer__content">
        <el-tabs
          :value="tabName"
          class="user-detail-tabs-wrap"
          tab-position="left"
          type="border-card"
          @tab-click="tabChange"
        >
          <!-- 编辑 -->
          <el-tab-pane name="edit">
            <span slot="label">
              <i class="iconfont iconicon_detail"></i>
            </span>

            <div class="detail-title flex-space-between">
              <p class="title fs16">详细信息</p>
              <el-button
                v-if="isEdit"
                round
                type="primary"
                @click="editUser"
              >
                <i class="iconfont iconicon_edit"></i>
                编辑
              </el-button>
            </div>

            <user-info
              ref="userInfo"
              :class="isEdit ? '' : 'editshow'"
              :current-user="currentUser"
              :edit-login-name="true"
              :is-edit="isEdit"
            ></user-info>
            <!-- 底部操作 -->
            <footer-btn
              ref="editFooter"
              :class="isEdit ? '' : 'footerbtnshow'"
              @cancel="cancelEdit"
              @submitSave="saveEdit"
            ></footer-btn>
          </el-tab-pane>

          <el-dialog
            :visible.sync="delUserError"
            append-to-body
            class="dialog-wrap editdialog"
            title="提示"
            width="400px"
            @close="closeErrorDialog"
          >{{ delName }}</el-dialog>


        </el-tabs>
      </div>
    </drawer>


  </div>
</template>

<script>
import {
  validateEmail,
  validatePhone,
  validateTelephone
} from '@/utils/validate'
import OperateArea from '@/components/OperateArea/usersIndex'
import Drawer from '@/components/Drawer/index'
import Pagination from '@/components/Pagination/index'
import Popover from '@/components/Popover/index'
import UserInfo from './userInfo.vue'
import FooterBtn from './footerBtn.vue'
import operateBtn from '@/components/CancelAndSubmitBtnGroup'
import { authTranslation } from '@/utils/auth-translation'
import {
  queryUserList,
  addUser,
  deleteUser,
  enableUser,
  disableUser,
  copyAddUser,
  viewUser,
  updateUser,
  getSpaceSelect
} from '@/api/adminPage/userManage/user'

export default {
  name: 'User',
  components: {
    OperateArea,
    Pagination,
    UserInfo,
    FooterBtn,

    Drawer,
    Popover,
    operateBtn
  },
  data() {
    var checkPsw = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.pswForm.password) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }
    return {
      pswForm: {
        password: '',
        pswSecond: ''
      },
      btnText: {
        add: '添加',
        del: '删除'
      },
      pswRules: {
        password: [
          { min: 6, max: 15, message: '密码必须为6到15位的英文数字组合', trigger: 'blur' },
          { required: true, message: '请输入需要更改成的密码', trigger: 'blur' }
        ],
        pswSecond: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: checkPsw, trigger: 'blur' }
        ]
      },
      selectUser: {},
      tableData: [],
      searchVal: '',
      pageNo: 1,
      pageSize: 10,
      total: 0,
      delUserError: false,
      dialogAddUser: false,
      formAddUser: {
        loginName: '',
        surname: '',
        name: '',
        email: '',
        telephone: '',
        fixedlineTelephone: '',
        address: '',
        city: '',
        postalCode: '',
        fileServer: '默认',
        allWorkspace: '0',
        status: '0', // 0-未启用   1-是启用
        remark: ''
      },
      loading: false,
      ruleAddUser: {
        loginName: [
          { required: true, message: '请输入登录名', trigger: 'blur' }
        ],
        surname: [{ required: true, message: '请输入姓', trigger: 'blur' }],
        name: [{ required: true, message: '请输入名', trigger: 'blur' }],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }
        ],
        telephone: [{ validator: validatePhone, trigger: 'blur' }],
        fixedlineTelephone: [{ validator: validateTelephone, trigger: 'blur' }]
      },
      multipleSelection: [],
      isCopy: 0, // 1-另存 0-新增
      dialogUserDetail: false,
      currentUser: {},
      isEdit: true, // true-非编辑状态 false-编辑状态
      tDataUserGroup: [],
      tDataRole: [],
      tDataWorkSpace: [],
      tabName: 'edit',
      tLoading: false,
      visiblePop: false,
      curtWorkSpace: {},
      wsLoading: false,
      resetPswDialog: false,
      singleUser: {},
      id: '',
      delName: [],
      delConfirm: []
    }
  },
  computed: {
    records() {
      return this.multipleSelection.length
    }
  },
  created() {
    this.getUserList()
  },

  methods: {
    submitReset() {
      this.$refs['pass'].validate(valid => {
        if (valid) {
          this.singleUser[0].oldpassword = ''
          this.singleUser[0].password = this.pswForm.password
          updateUser(this.singleUser[0]).then(res => {
            this.$message({
              type: 'success',
              message: '重置密码成功'
            })
          })

          this.resetPswDialog = false
        }
      })
    },
    closeResetDialog() {
      this.resetPswDialog = false
      this.pswForm = {}
      if (this.$refs['pass']) {
        this.$nextTick(function() {
          this.$refs['pass'].clearValidate()
        })
      }
    },
    closeResetDIALOG() {
      this.resetPswDialog = false
      this.pswForm = {}
      if (this.$refs['pass']) {
        this.$nextTick(function() {
          this.$refs['pass'].clearValidate()
        })
      }
    },
    closeErrorDialog() {
      this.delConfirm = []
      this.delName = []
      this.delUserError = false
    },
    closeDrawer() {
      this.dialogAddUser = false
      console.log(1111)
      if (this.$refs.addUser.$refs.addUserDrawer) {
        // 延时执行
        this.$nextTick(function() {
          console.log(222)
          this.$refs.addUser.$refs.addUserDrawer.clearValidate()
        })
      }
    },
    // tableRowClassName({ row }) {
    //   if (row.admin === 1) {
    //     return 'adminC'
    //   }
    //   return ''
    // },
    selectable(row, index) {
      if (row.admin === '1') {
        return false
      } else {
        return true
      }
    },
    getUserList(value) {
      if (value && typeof value === 'object') {
        this.pageNo = value.page
        this.pageSize = value.limit
      }
      const params = {
        pageNo: this.pageNo > 0 ? this.pageNo : 1,
        pageSize: this.pageSize,
        queryStr: this.searchVal,
        status: ''
      }
      this.tLoading = true
      queryUserList(params).then(res => {
        this.tLoading = false
        const records = res.result.records
        console.log(records)
        if (records !== null) {
          records.forEach((item, index) => {
            // 非全部工作区
            if (item.allWorkspace === '1') {
              if (item.workspaces !== null) {
                const spaceList = []
                item.workspaces.forEach((space, index) => {
                  spaceList.push(space.workspaceName)
                })
                item.workspaces = spaceList.join('、')
              }
            }
          })
          this.tableData = records
          this.total = res.result.total
        } else {
          this.tableData = []
          this.total = 0
        }
      })
    },
    filterTag(value, row, column) {
      const property = column['property']
      return row[property] === value
    },
    addUser() {
      this.formAddUser = {
        loginName: '',
        name: '',
        userName: '',
        email: '',
        telephone: '',
        fixedlineTelephone: '',
        address: '',
        city: '',
        postalCode: '',
        fileServer: '默认',
        allWorkspace: '0',
        status: '1',
        remark: ''
      }
      this.isCopy = 0
      this.dialogAddUser = true
    },
    submitAddUser() {
      this.$refs.addUser.$refs.addUserDrawer.validate(valid => {
        if (valid) {
          if (this.isCopy === 1) {
            // 另存
            copyAddUser(this.formAddUser).then(res => {
              this.getUserList()
              this.dialogAddUser = false
            })
          } else {
            addUser(this.formAddUser).then(res => {
              this.getUserList()
              this.dialogAddUser = false
            })
          }
        }
      })
    },
    handleClose(done) {
      this.dialogAddUser = false
    },
    handleSelectionChange(val) {
      this.singleUser = val
      if (val.length) {
        this.$refs.operateArea.$children[1].selectIndex = val.length
      } else {
        this.$refs.operateArea.$children[1].selectIndex = -1
      }
      this.multipleSelection = val
    },
    delUser() {
      if (this.records === 0) {
        this.$message({
          message: '请选择需要删除的用户'
        })
      } else {
        this.handleDel()
      }
    },
    getOperateIds() {
      const ids = []
      this.multipleSelection.forEach((item, index) => {
        ids.push(item.id)
      })
      return ids
    },
    handleDel() {
      const ids = this.getOperateIds()
      // ids.forEach((val, index, arr) => {
      //   console.log(val)
      //   getUserRoleOrWorkSpace(val).then(res => {
      //     console.log(res.result)
      //     if (res.result.workspaces) {
      //       console.log(2222)
      //       this.delName.push(res.result.userName)
      //     } else {
      //       this.delConfirm.push(val)
      //     }
      //   })
      // })
      // console.log('wwww', this.delName)
      // console.log('qqqq', this.delConfirm)
      // if (this.delConfirm.length !== 0) {
      deleteUser(ids).then(res => {
        if (res.result) {
          this.$message({
            message: '以下用户存在工作区绑定: ' + res.result,
            type: 'error'
          })
        } else {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
        }
        this.getUserList()
      })
      // }
      if (this.delName.length !== 0) {
        console.log(112211)
        this.delUserError = true
      }
    },
    enUser() {
      if (this.records === 0) {
        this.$message({
          message: '请选择需要启用的用户'
        })
      } else {
        this.handleEnable()
      }
    },
    handleEnable() {
      const ids = this.getOperateIds()
      enableUser(ids).then(res => {
        this.$message({
          message: '启用成功',
          type: 'success'
        })
        this.getUserList()
      })
    },
    disUser() {
      if (this.records === 0) {
        this.$message({
          message: '请选择需要禁用的用户'
        })
      } else {
        this.handleDisable()
      }
    },
    handleDisable() {
      const ids = this.getOperateIds()
      disableUser(ids).then(res => {
        this.$message({
          message: '禁用成功',
          type: 'success'
        })
        this.getUserList()
      })
    },
    handleReset() {
      console.log(111)
      this.resetPswDialog = true
    },
    copySave(item) {
      this.formAddUser = {
        loginName: item.loginName,
        surname: item.surname,
        name: item.name,
        email: item.email,
        telephone: item.telephone,
        fixedlineTelephone: item.fixedlineTelephone,
        address: item.address,
        city: item.city,
        postalCode: item.postalCode,
        fileServer: '默认',
        allWorkspace: item.allWorkspace,
        status: item.status,
        remark: item.remark
      }
      this.isCopy = 1
      this.dialogAddUser = true
    },
    checkUserDetail(item) {
      this.tabName = 'edit'
      console.log(item.id)
      viewUser(item.id).then(res => {
        console.log(res)
        this.currentUser = res.result
        this.currentUser.id = item.id
        this.dialogUserDetail = true
      })
    },
    handleCloseDetail() {
      this.dialogUserDetail = false
    },
    editUser() {
      this.isEdit = false
    },
    cancelEdit() {
      this.isEdit = true
      // this.dialogUserDetail = false
    },
    saveEdit() {
      if (this.isEdit) {
        this.$message({
          message: '你未编辑用户信息，无需保存'
        })
        return
      }
      this.$refs.editFooter.loading = true
      this.$refs.userInfo.$refs.addUserDrawer.validate(valid => {
        if (valid) {
          this.currentUser.oldpassword = ''
          console.log(this.currentUser)
          updateUser(this.currentUser).then(res => {
            this.isEdit = true
            // this.dialogUserDetail = false
            this.getUserList()
            this.$message({
              message: '保存成功',
              type: 'success'
            })
          })
        }
        this.$refs.editFooter.loading = false
      })
    },
    tabChange(params) {
      this.tabName = params.name
      switch (params.name) {
        case 'userGroup':
          this.queryUserGroupInfo()
          break
        case 'role':
        case 'workSpace':
          this.queryUserRoleOrWorkSpace()
          break
      }
    },
    queryUserGroupInfo() {
      this.wsLoading = true
      getUserGroup(this.currentUser.id).then(res => {
        this.wsLoading = false
        const resData = res.result.sysUsergroups
        if (resData !== null) {
          const tData = []
          resData.forEach((item, index) => {
            const dataObj = { groupName: '', space: [] }
            dataObj.groupName = item.name
            if (item.workspaces !== null) {
              item.workspaces.forEach((space, index) => {
                dataObj.space.push(space.workspaceName)
              })
              dataObj.space = dataObj.space.join('、')
            }
            tData.push(dataObj)
          })
          this.tDataUserGroup = tData
        }
      })
    },
    queryUserRoleOrWorkSpace() {
      this.wsLoading = true
      getUserRoleOrWorkSpace(this.currentUser.id).then(res => {
        this.wsLoading = false
        const resData = res.result
        this.tDataRole = resData.roles
        if (resData.workspaces !== null) {
          const work = resData.workspaces
          work.forEach((item, index) => {
            if (item.sysWorkspaceUser.authority === null) {
              item.authorityText = '只读'
            } else {
              item.authorityText = authTranslation(
                item.sysWorkspaceUser.authority
              )
            }
          })
          this.tDataWorkSpace = resData.workspaces
        } else {
          this.tDataWorkSpace = []
        }
      })
    },
    delSpaceSubmit(item) {
      deleteSysUserWork(item.sysWorkspaceUser.id).then(res => {
        this.queryUserRoleOrWorkSpace()
        this.$message({ message: '删除成功', type: 'success' })
      })
    },
    addSpace() {
      this.selectSpace()
      this.$refs.addWS.dialogVisible = true
    },
    selectSpace() {
      console.log(this.currentUser.id)
      getSpaceSelect(this.currentUser.id).then(res => {
        console.log(res)
        this.$refs.addWS.workSpaceList = res.result === '' ? [] : res.result
      })
    },
    cancelAdd() {
      this.dialogAddUser = false
    },
    addWorkSpace(formData) {
      const params = {
        authority: formData.authority,
        userId: this.currentUser.id,
        workspaceId: formData.workSpaceId
      }
      addSysUserWork(params).then(res => {
        this.queryUserRoleOrWorkSpace()
        this.$refs.addWS.dialogVisible = false
        this.$message({
          message: '新增成功',
          type: 'success'
        })
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import "~@/assets/styles/variables";
@import "~@/assets/styles/user-drawer.scss";
// ::v-deep .el-table .adminC {
// }
.cup {
  cursor: pointer;
}
::v-deep .el-table tbody tr:hover > td {
  cursor: pointer;
}
::v-deep .user-detail-tabs-wrap {
  height: calc(100vh - 67px);
  border: none;
  .detail-title {
    margin-bottom: 25px;
    color: $fontColor;
  }
  .el-tabs__header {
    margin-right: 0;
    background: $background;
  }
  .el-tabs__item {
    padding: 0 13px;
    height: 59px;
    line-height: 59px;
  }
  .el-tabs__content {
    padding: 16px;
  }
  // .user-detail-scroll{
  //   margin-bottom: 68px;
  //   height: calc(100vh - 136px);
  // }
}
// ::v-deep .el-dialog {
//   .el-form {
//     .el-input__inner {
//       width: 250px;
//     }
//   }
// }
</style>
